package com.xiaobai.service.imageRecognition;

import com.xiaobai.service.addition.HealthReportService_v2;
import com.xiaobai.units.PytorchSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

/**
 * @description:
 * @author: 小白白
 * @create: 2021-12-11
 **/

@Service("pyValidCode")
@Slf4j
public class PyValidCode implements IValidCode {

    private static ThreadLocal<String> fileUrlThreadLocal = new ThreadLocal<>();

    @Override
    public String figureCaptcha(byte[] imageBytes) {
        return imageCodePython(imageBytes);
    }

    @Override
    public void saveImageFile() {
        fileUrlThreadLocal.remove();
    }

    @Override
    public void cancelSave() {
        File file = new File(fileUrlThreadLocal.get());
        log.info("删除文件:" + fileUrlThreadLocal.get());
        file.delete();
        fileUrlThreadLocal.remove();
    }

    /**
     * python程序识别验证码
     * 必须存储文件
     */
    private String imageCodePython(byte[] bytes) {
        String filePath; // 先默认AAAA
        try {
            filePath = saveFile(bytes, "AAAA");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        PytorchSocket.CodeTask codeTask = new PytorchSocket.CodeTask(filePath);
        PytorchSocket.addTask(codeTask);
        String code;
        try {
            code = codeTask.getResult();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        }
        code = code.trim();
        File file = new File(filePath);
        String oldName = file.getName();
        String newName = code + oldName.substring(4);
        filePath = filePath.substring(0, filePath.lastIndexOf(File.separator) + 1) + newName;
        file.renameTo(new File(filePath));
        fileUrlThreadLocal.set(filePath);
        return code;
    }

    private static Random random = new Random();

    private static String saveFile(byte[] bytes, String code) throws IOException {
        int randomI = random.nextInt(10000);
        double randomD = random.nextDouble();
        // 随意定义4个字母即可
        String filePah = HealthReportService_v2.IMAGES_PATH
                + code + "_" + randomD + randomI + (System.currentTimeMillis() / 1000000) + ".png";
        File file = new File(filePah);
        FileOutputStream os = new FileOutputStream(file);
        os.write(bytes, 0, bytes.length);
        os.close();
        // 返回文件路径名
        return filePah;
    }

}
